package com.yuexunit.mobilenurse.module.Login.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.shelwee.update.UpdateHelper;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.AppContext;
import com.yuexunit.mobilenurse.base.search.honeywell.HoneyWellConfig;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.Lesions.ui.Act_LesionList;
import com.yuexunit.mobilenurse.module.Login.bean.Login_Bq;
import com.yuexunit.mobilenurse.module.Login.bean.SystemConfig;
import com.yuexunit.mobilenurse.module.Login.bean.SystemConfigDate;
import com.yuexunit.mobilenurse.module.Login.bean.YXLoginData;
import com.yuexunit.mobilenurse.module.Login.model.impl.LoginModel;
import com.yuexunit.mobilenurse.module.Login.presenter.IUserPresenter;
import com.yuexunit.mobilenurse.module.Login.presenter.impl.UserPresenter;
import com.yuexunit.mobilenurse.module.Login.ui.view.IUserView;
//import com.yuexunit.mobilenurse.module.Patients.ui.Act_Main_IData;
import com.yuexunit.mobilenurse.module.Patients.ui.Act_Main_HoneyWell;
import com.yuexunit.mobilenurse.module.Patients.ui.Act_Main_Lachsis;
import com.yuexunit.mobilenurse.util.PermissionUtils;
import com.yuexunit.mobilenurse.util.RxUtils;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by 姚平 on 2015/12/8.
 * <p>
 * 登录界面
 */
public class Act_Login extends KJActivity implements IUserView ,ActivityCompat.OnRequestPermissionsResultCallback{

    @Bind(R.id.username_edit)
    public EditText username;
    @Bind(R.id.password_edit)
    public EditText password;
    @Bind(R.id.vewsionname)
    public TextView vewsionname;

    private IUserPresenter userPresenter;

    //三判断值，判断三个访问接口下拉数据各自是否成功
    public boolean isgetJCK = false;

    //病区列表
    ArrayList<Login_Bq> Bqlist = new ArrayList<Login_Bq>();
    //记录Log
    private final Logger log = LoggerFactory.getLogger(Act_Login.class);
    LoadingDialog dialog;



    @Override
    public void setRootView() {
        setContentView(R.layout.act_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 23) {
            PermissionUtils.requestMultiPermissions(this, mPermissionGrant);
        }

        //显示版本号
        try {
            vewsionname.setText(getPackageManager().getPackageInfo(getPackageName(),0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initData() {
        super.initData();
        HoneyWellConfig.HoneyWell_Create(this);
        username.setText("");
        password.setText("");

        //获取服务器上的版本号，进行判断，是否要下载最新APK进行更新
        AppVersionCheck();
        dialog = new LoadingDialog(this);
        userPresenter = new UserPresenter(this, new LoginModel());
        userPresenter.getListParams();
    }

//    @Override
//    public void onResume(){
//        super.onResume();
//        username.setText(PreferenceHelper.readString(aty, AppConfig.LOGIN_INFO, AppConfig.LOGIN_NAME));
//        password.setText(PreferenceHelper.readString(aty, AppConfig.LOGIN_INFO, AppConfig.LOGIN_PASSWORD));
//    }

    @OnClick(R.id.login)
    public void Login() {
        if (SystemTool.checkNet(aty)) {

            if (CheckDownload()) {
                userPresenter.doInLogin(username.getText().toString(), password.getText().toString());

            } else {
                ViewInject.toast("基本服务配置未成功,请点击登录按钮重试..");
            }
        } else {
            ViewInject.toast("网络连接失败..请检查网络..");
        }
    }

    @Override
    public void doInLogin(YXLoginData yxLoginData) {
//        //保存上次登录账号信息
//        PreferenceHelper.write(aty,AppConfig.LOGIN_INFO,AppConfig.LOGIN_NAME,username.getText().toString());
//        PreferenceHelper.write(aty,AppConfig.LOGIN_INFO,AppConfig.LOGIN_PASSWORD,password.getText().toString());

        String filename = AppConfig.NURSE_INFO;
        AppConfig.NURSEID = yxLoginData.getResponse().getEmpinfo().getLogid();
        PreferenceHelper.write(aty, filename, AppConfig.NURSE_LOGID, yxLoginData.getResponse().getEmpinfo().getLogid());
        PreferenceHelper.write(aty, filename, AppConfig.NURSE_LOGNAME, yxLoginData.getResponse().getEmpinfo().getLogname());
        PreferenceHelper.write(aty, filename, AppConfig.NURSE_DEPTNO, yxLoginData.getResponse().getEmpinfo().getDeptno());
        PreferenceHelper.write(aty, filename, AppConfig.NURSE_DEPTNAME, yxLoginData.getResponse().getEmpinfo().getDeptname());
        List<Login_Bq> login_bqs;
        String bqs = yxLoginData.getResponse().getWardlist();
        String bqs_first = bqs.substring(0, 1);
        if (!bqs_first.equals("[")) {
            bqs = "[" + bqs + "]";
            login_bqs = JSON.parseArray(bqs, Login_Bq.class);
        } else {
            login_bqs = JSON.parseArray(bqs, Login_Bq.class);
        }

        if (login_bqs != null) {
            Bqlist.clear();
            for (int i = 0; i < login_bqs.size(); i++) {
                Login_Bq login_bq = new Login_Bq();
                login_bq = login_bqs.get(i);
                Bqlist.add(login_bq);
            }
            ((AppContext) getApplication()).setBqlist(Bqlist);
            if(Bqlist.size()==1)
            {
                PreferenceHelper.write(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_ID, Bqlist.get(0).getWardno());
                PreferenceHelper.write(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_NAME, Bqlist.get(0).getWardname());
                //Intent intent = new Intent(aty,Act_Main_Moto.class);
//                Intent intent = new Intent(aty, Act_Main_HoneyWell.class);
//                Intent intent = new Intent(aty, Act_Main_Normal.class);
//                Intent intent = new Intent(aty, Act_Main_Advantech.class);
                Intent intent = new Intent(aty, Act_Main_Lachsis.class);
//                Intent intent = new Intent(aty, Act_Main_BayNexus.class);
//                Intent intent = new Intent(aty, Act_Main_M80.class);
//                Intent intent = new Intent(aty, Act_Main_Joyree.class);
//                Intent intent = new Intent(aty, Act_Main_Techain.class);
//                Intent intent = new Intent(aty, Act_Main_Seuic.class);
//                Intent intent = new Intent(aty, Act_Main_IData.class);
                startActivity(intent);
            }
            else {
                showActivity(aty, Act_LesionList.class);
            }
        }

        username.setText("");
        password.setText("");
    }

    @Override
    public void saveSystemListParams(SystemConfig systemConfig) {
        String filename = AppConfig.JCI_INFO;
        PreferenceHelper.write(aty, filename, AppConfig.JCI_BYJ, JSON.parseObject(systemConfig.getByj(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_BYJ_RULE, JSON.parseObject(systemConfig.getByj_rule(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_WD, JSON.parseObject(systemConfig.getWd(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_WD_RULE, JSON.parseObject(systemConfig.getWd_rule(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_PTSM, JSON.parseObject(systemConfig.getPtsm(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_PTSM_RULE, JSON.parseObject(systemConfig.getPtsm_rule(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_CX_RULE, JSON.parseObject(systemConfig.getCx_rule(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_ENABLE, JSON.parseObject(systemConfig.getEnabled(), SystemConfigDate.class).getValue());
        PreferenceHelper.write(aty, filename, AppConfig.JCI_JCI, JSON.parseObject(systemConfig.getJci(), SystemConfigDate.class).getValue());
//        PreferenceHelper.write(aty, filename, AppConfig.JCI_YX_RULE, JSON.parseObject(systemConfig.getYx_rule(), SystemConfigDate.class).getValue());

        isgetJCK = true;
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;

            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;

        }
    }

    @Override
    public void loadingToastStatus(String Content) {
        ViewInject.toast(Content);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HoneyWellConfig.HoneyWell_Destory();
        RxUtils.unsubscribeIfNotNull(((UserPresenter) userPresenter).compositeSubscription);
    }

    //判断接口下拉数据哪个没获取成功，重新获取
    public boolean CheckDownload() {

        if (!this.isgetJCK) {
            userPresenter.getListParams();
        }
        return this.isgetJCK;
//        return true;
    }

    //检验版本并判断是否更新APK
    private void AppVersionCheck() {

        //UpdateHelper第三方插件进行的更新版本功能
        UpdateHelper updateHelper = new UpdateHelper.Builder(this)
                .checkUrl(AppConfig.CHECK_APP_LASTVERSION)
//                .checkUrl("http://192.168.1.126:8080/version/last")
                .isAutoInstall(true) //设置为false需在下载完手动点击安装;默认值为true，下载后自动安装。
                .build();
        updateHelper.check();
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_RECORD_AUDIO:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_RECORD_AUDIO", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_GET_ACCOUNTS:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_GET_ACCOUNTS", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_READ_PHONE_STATE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_READ_PHONE_STATE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_CALL_PHONE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_CALL_PHONE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_CAMERA:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_CAMERA", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_ACCESS_FINE_LOCATION", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_ACCESS_COARSE_LOCATION:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_ACCESS_COARSE_LOCATION", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_READ_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_MULTI_PERMISSION:
                    Toast.makeText(Act_Login.this, "Result All Permission Grant", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

}